import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:schoollifedemo/business/school/viewmodel/home_school_page_viewmodel.dart';
import 'package:schoollifedemo/commonwidget/circle_empty_widget.dart';
import 'package:schoollifedemo/commonwidget/common_base_page.dart';
import 'package:schoollifedemo/commonwidget/common_dialog.dart';
import 'package:schoollifedemo/commonwidget/loading_widget.dart';
import 'package:schoollifedemo/commonwidget/text_widget_with_overflow.dart';
import 'package:schoollifedemo/entity/Entity.dart';

class SchoolPage extends BaseStatefulPage {
  const SchoolPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SchoolPageState();
  }
}

class _SchoolPageState extends BasePageState<SchoolPage> {
  final HomeSchoolPageViewModel _viewModel = HomeSchoolPageViewModel();
  Color _defaultEmptyMemorandumColor = const Color(0x66D0E7FF);

  final _unTouchColor = const Color(0x66D0E7FF);
  final _touchColor = const Color(0xFF429CFF);

  @override
  void initState() {
    _viewModel.init();
    _viewModel.pullUserMemorandumList();
    _viewModel.pullSchoolAnnouncement();
    _viewModel.pullStudentSource();
    super.initState();
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        padding: const EdgeInsets.only(bottom: 10),
        child: MediaQuery.removePadding(
          removeTop: true,
          context: context,
          child: RefreshIndicator(
            onRefresh: () async {
              // refresh
              _viewModel.pullUserMemorandumList(refreshQuickly: true);
              _viewModel.pullSchoolAnnouncement();
              _viewModel.pullStudentSource();
            },
            child: ListView(
              physics: const BouncingScrollPhysics(),
              children: [
                // _applicationWidget(),
                //
                // /// 学生课程信息
                // StreamBuilder(
                //   stream: _viewModel.sourceLoadingState,
                //   initialData: CommonLoadingState.loading,
                //   builder: (buildContext, snapshot) {
                //     final studentCourseLoadingState =
                //         snapshot.data as CommonLoadingState?;
                //     switch (studentCourseLoadingState) {
                //       case CommonLoadingState.loading:
                //         return _studentCourseWidget(isLoading: true);
                //       case CommonLoadingState.successTypeOne:
                //       case CommonLoadingState.successTypeTwo:
                //         return _studentCourseWidget(isLoading: false);
                //       default:
                //         return Container();
                //     }
                //   },
                // ),

                /// 备忘录信息
                StreamBuilder(
                  stream: _viewModel.memorandumLoadingState,
                  initialData: CommonLoadingState.loading,
                  builder: (buildContext, snapshot) {
                    final memorandumLoadingState =
                        snapshot.data as CommonLoadingState?;
                    switch (memorandumLoadingState) {
                      case CommonLoadingState.loading:
                        return _recordTextWidget(isLoading: true);
                      case CommonLoadingState.successTypeOne:
                      case CommonLoadingState.successTypeTwo:
                        return _recordTextWidget(isLoading: false);
                      default:
                        return Container();
                    }
                  },
                ),

                /// 学校公告
                StreamBuilder(
                  stream: _viewModel.schoolNoticeLoadingState,
                  initialData: CommonLoadingState.loading,
                  builder: (buildContext, snapshot) {
                    final schoolNoticeLoadingState =
                        snapshot.data as CommonLoadingState?;
                    switch (schoolNoticeLoadingState) {
                      case CommonLoadingState.loading:
                        return _schoolWidget(isLoading: true);
                      case CommonLoadingState.successTypeOne:
                      case CommonLoadingState.successTypeTwo:
                        return _schoolWidget(isLoading: false);
                      default:
                        return Container();
                    }
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _applicationWidget() {
    return Column(
      children: [
        const Padding(
          padding: EdgeInsets.only(top: 10, left: 10),
          child: TextWidgetWithOverflow(
            '应用',
            insideColor: Colors.transparent,
            fontSize: 28,
            textAlign: TextAlign.left,
            width: double.infinity,
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(left: 15, right: 15),
          child: CircleEmptyWidget(
            Container(
              margin: const EdgeInsets.all(15),
              child: GridView.builder(
                physics: const BouncingScrollPhysics(),
                scrollDirection: Axis.horizontal,
                itemCount: 20,
                itemBuilder: (buildContext, index) {
                  return CircleEmptyWidget(
                    Container(),
                  );
                },
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 5,
                  mainAxisSpacing: 5,
                  mainAxisExtent: 80,
                ),
              ),
            ),
            height: 120,
            width: double.infinity,
            insideColor: const Color(0x66D0E7FF),
          ),
        ),
      ],
    );
  }

  Widget _schoolWidget({required bool isLoading}) {
    return Column(
      children: [
        const Padding(
          padding: EdgeInsets.only(top: 10, left: 10),
          child: TextWidgetWithOverflow(
            '学校公告',
            insideColor: Colors.transparent,
            fontSize: 28,
            textAlign: TextAlign.left,
            width: double.infinity,
          ),
        ),
        isLoading
            ? _loadingWidget()
            : Padding(
                padding: const EdgeInsets.only(left: 15, right: 15),
                child: CircleEmptyWidget(
                  Container(
                    margin: const EdgeInsets.only(top: 20, bottom: 10),
                    child: Column(
                      children: [
                        Container(
                          margin: const EdgeInsets.only(left: 15, right: 15),
                          child: ListView.separated(
                            physics: const NeverScrollableScrollPhysics(),
                            shrinkWrap: true,
                            itemBuilder: (builder, index) {
                              SchoolAnnouncementEntity? announcement =
                                  _viewModel.schoolAnnouncementResp
                                      ?.announcementList?[index];
                              return GestureDetector(
                                onTap: () {
                                  _viewModel.turnToSingleAnnouncementPage(
                                    context,
                                    mainTitle: announcement?.mainTitle ?? '',
                                  );
                                },
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: TextWidgetWithOverflow(
                                        announcement?.mainTitle ?? '',
                                        fontSize: 16,
                                        textAlign: TextAlign.left,
                                        paddingLeft: 20,
                                        paddingRight: 20,
                                        paddingTop: 8,
                                        paddingBottom: 8,
                                      ),
                                    ),
                                    const TextWidgetWithOverflow(
                                      '更多',
                                      fontSize: 12,
                                      width: 50,
                                      insideColor: Colors.transparent,
                                    )
                                  ],
                                ),
                              );
                            },
                            separatorBuilder: (builder, index) {
                              return Container(
                                height: 5,
                              );
                            },
                            itemCount: _viewModel.schoolAnnouncementResp
                                    ?.announcementList?.length ??
                                0,
                          ),
                        ),
                        _viewModel.schoolAnnouncementResp?.announcementList
                                    ?.isNotEmpty ==
                                true
                            ? GestureDetector(
                                onTap: () {
                                  _viewModel
                                      .turnToMultiAnnouncementPage(context);
                                },
                                child: Container(
                                  margin: const EdgeInsets.only(
                                    bottom: 10,
                                    right: 10,
                                    left: 10,
                                    top: 10,
                                  ),
                                  child: const TextWidgetWithOverflow(
                                    '查看更多',
                                    fontSize: 14,
                                    width: double.infinity,
                                    insideColor: Colors.transparent,
                                    textAlign: TextAlign.right,
                                  ),
                                ),
                              )
                            : GestureDetector(
                                onTap: () {
                                  Fluttertoast.showToast(
                                    msg: '功能未完善',
                                    gravity: ToastGravity.CENTER,
                                  );
                                },
                                child: const TextWidgetWithOverflow(
                                  '设置学校官网信息',
                                  fontSize: 18,
                                  insideColor: Colors.transparent,
                                ),
                              ),
                      ],
                    ),
                  ),
                  width: double.infinity,
                  insideColor: const Color(0x66D0E7FF),
                ),
              ),
      ],
    );
  }

  Widget _studentCourseWidget({required bool isLoading}) {
    return Column(
      children: [
        const Padding(
          padding: EdgeInsets.only(top: 10, left: 10),
          child: TextWidgetWithOverflow(
            '学生课程',
            insideColor: Colors.transparent,
            fontSize: 28,
            textAlign: TextAlign.left,
            width: double.infinity,
          ),
        ),
        isLoading
            ? _loadingWidget()
            : Padding(
                padding: const EdgeInsets.only(left: 15, right: 15),
                child: CircleEmptyWidget(
                  Column(),
                  height: 200,
                  width: double.infinity,
                  insideColor: const Color(0x66D0E7FF),
                ),
              ),
      ],
    );
  }

  Widget _recordTextWidget({required bool isLoading}) {
    int maxListLength =
        (_viewModel.userMemorandumResp?.memorandumList?.length ?? 0);
    return Column(
      children: [
        const Padding(
          padding: EdgeInsets.only(top: 10, left: 10),
          child: TextWidgetWithOverflow(
            '你的备忘录',
            insideColor: Colors.transparent,
            fontSize: 28,
            textAlign: TextAlign.left,
            width: double.infinity,
          ),
        ),
        isLoading
            ? _loadingWidget()
            : Padding(
                padding: const EdgeInsets.only(left: 15, right: 15),
                child: CircleEmptyWidget(
                  Container(
                    margin: const EdgeInsets.only(
                      left: 12,
                      right: 12,
                      top: 15,
                      bottom: 15,
                    ),
                    child: Column(
                      children: [
                        ListView.separated(
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemBuilder: (builder, index) {
                            final memorandumItem = _viewModel
                                .userMemorandumResp?.memorandumList?[index];
                            return GestureDetector(
                              onTap: () async {
                                await _viewModel.turnToSingleMemorandumPage(
                                    context,
                                    noteId: memorandumItem?.noteId ?? '');
                                _viewModel.pullUserMemorandumList(
                                  refreshQuickly: true,
                                  onSuccess: () {
                                    setState(() {});
                                  },
                                );
                              },
                              child: Container(
                                margin:
                                    const EdgeInsets.only(left: 5, right: 5),
                                child: TextWidgetWithOverflow(
                                  '备忘录${index + 1}: ' +
                                      (memorandumItem?.title ??
                                          memorandumItem?.msg ??
                                          ''),
                                  fontSize: 16,
                                  paddingBottom: 8,
                                  paddingTop: 8,
                                  paddingLeft: 20,
                                  paddingRight: 20,
                                  textAlign: TextAlign.left,
                                ),
                              ),
                            );
                          },
                          separatorBuilder: (builder, index) {
                            return Container(
                              height: 5,
                            );
                          },
                          itemCount: maxListLength < 5 ? maxListLength : 5,
                        ),
                        maxListLength == 0
                            ? GestureDetector(
                                onTapDown: (details) {
                                  _defaultEmptyMemorandumColor = _touchColor;
                                  setState(() {});
                                },
                                onTapUp: (details) async {
                                  _defaultEmptyMemorandumColor = _unTouchColor;
                                  setState(() {});
                                  // 跳转到编辑界面
                                  await _viewModel.turnToEditMemorandumPage(
                                    context,
                                    isEditMode: true,
                                  );
                                  _viewModel.pullUserMemorandumList(
                                    refreshQuickly: true,
                                    onSuccess: () {
                                      setState(() {});
                                    },
                                    onFailure: (msg) {
                                      DialogUtils.showTitleAndMessageDialog(
                                        context,
                                        clickOutSideDismiss: true,
                                        title: "错误",
                                        msg: '$msg',
                                      );
                                    },
                                  );
                                },
                                child: Container(
                                  margin:
                                      const EdgeInsets.only(top: 5, bottom: 5),
                                  child: const TextWidgetWithOverflow(
                                    '点击添加你的备忘录',
                                    fontSize: 15,
                                    insideColor: Colors.transparent,
                                    width: double.infinity,
                                  ),
                                ),
                              )
                            : Container(
                                margin: const EdgeInsets.only(top: 10),
                                child: Row(
                                  children: [
                                    GestureDetector(
                                      onTap: () async {
                                        // 跳转到编辑界面
                                        await _viewModel
                                            .turnToEditMemorandumPage(
                                          context,
                                          isEditMode: true,
                                        );
                                        _viewModel.pullUserMemorandumList(
                                          refreshQuickly: true,
                                          onSuccess: () {
                                            setState(() {});
                                          },
                                          onFailure: (msg) {
                                            DialogUtils
                                                .showTitleAndMessageDialog(
                                              context,
                                              clickOutSideDismiss: true,
                                              title: "错误",
                                              msg: '$msg',
                                            );
                                          },
                                        );
                                      },
                                      child: Row(
                                        children: [
                                          Container(
                                            margin:
                                                const EdgeInsets.only(left: 10),
                                            child: const Icon(
                                                Icons.add_circle_outline),
                                          ),
                                          const TextWidgetWithOverflow(
                                            '添加备忘录',
                                            fontSize: 15,
                                            insideColor: Colors.transparent,
                                            textAlign: TextAlign.left,
                                            width: 100,
                                          ),
                                        ],
                                      ),
                                    ),
                                    Expanded(
                                      child: GestureDetector(
                                        onTap: () async {
                                          await _viewModel
                                              .turnToAllMemorandumPage(context);
                                          _viewModel.pullUserMemorandumList(
                                              refreshQuickly: true,
                                              onSuccess: () {
                                                setState(() {});
                                              });
                                        },
                                        child: const TextWidgetWithOverflow(
                                          '更多',
                                          fontSize: 14,
                                          insideColor: Colors.transparent,
                                          textAlign: TextAlign.right,
                                          width: double.infinity,
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                      ],
                    ),
                  ),
                  width: double.infinity,
                  insideColor: _defaultEmptyMemorandumColor,
                ),
              ),
      ],
    );
  }

  Widget _loadingWidget() {
    return Container(
      height: 50,
      color: Colors.white,
      child: const LoadingWidget(),
    );
  }
}
